package br.com.spam.pipeline.iu;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Map.Entry;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import br.com.spam.pipeline.core.Register;

public class IU_RegisterBank extends JPanel
{
	private static final long serialVersionUID = -4655900200010106343L;

	private IU_Datashow parent;
	private JPanel registers;
	private JLabel label = new JLabel("Registradores", (int) CENTER_ALIGNMENT);
	private Map<Register, JTextField> registersValue = new HashMap<Register, JTextField>();

	public IU_RegisterBank(IU_Datashow parent)
	{
		this.parent = parent;
		this.setLayout(new BorderLayout());
		this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		this.add(this.label, BorderLayout.NORTH);
		this.label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		this.label.setBackground(Color.GRAY);

		this.parent.onPipelineChanged(new Observer()
		{
			@Override
			public void update(Observable o, Object arg)
			{
				if (IU_RegisterBank.this.registers != null)
				{
					IU_RegisterBank.this.remove(IU_RegisterBank.this.registers);
				}

				IU_RegisterBank.this.start();
				IU_RegisterBank.this.update();
				IU_RegisterBank.this.add(IU_RegisterBank.this.registers, BorderLayout.CENTER);
			}
		});

	}

	private void start()
	{
		this.registers = new JPanel();
		this.registers.setBackground(Color.WHITE);
		GridLayout layout = new GridLayout(0, 3);
		this.registers.setLayout(layout);

		for (Register r : this.parent.pipeline().getProcessor().enumerateRegisters())
		{
			JPanel thisRegisterPanel = new JPanel();
			thisRegisterPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 1));
			JLabel name = new JLabel(r.name());
			name.setPreferredSize(new Dimension(25, name.getPreferredSize().height));

			JTextField value = new JTextField();
			value.setPreferredSize(new Dimension(65, value.getPreferredSize().height));

			value.setEditable(false);
			this.registersValue.put(r, value);

			thisRegisterPanel.add(name);
			thisRegisterPanel.add(value);

			this.registers.add(thisRegisterPanel);
		}
	}

	public void update()
	{
		for (Entry<Register, JTextField> entry : this.registersValue.entrySet())
		{
			entry.getValue().setText(Integer.toString(entry.getKey().getPersistedValue()));
		}
	}

}
